import axios from 'axios'
import router from "@/router/index.js";

export const REQUEST_TOKEN_KEY = 'Authorization'
export const BASE_URL = process.env.VUE_APP_API_BASE_URL

// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: process.env.VUE_APP_API_BASE_URL,
  timeout: 10000, // 请求超时时间
  withCredentials: true, // 允许携带 cookie
  headers: {
    'Content-Type': 'application/json',
    'Tzdsj-Origin': 'pc',
  },
})

// 异常拦截处理器
function errorHandler(error) {
  if (error.response) {
    const { data = {}, status, statusText } = error.response

    // 403 无权限
    if (status === 403) {
      showNotify({
        type: 'danger',
        message: (data && data.message) || statusText,
      })
    }

    // 401 未登录/未授权
    if (status === 401 && data.result && data.result.isLogin) {
      showNotify({
        type: 'danger',
        message: 'Authorization verification failed',
      })
      // 如果你需要直接跳转登录页面
      // location.replace(loginRoutePath)
    }
  }
  return Promise.reject(error)
}

// 请求拦截器
function requestHandler(config) {
  const savedToken = localStorage.getItem('token')

  // 有token,让每个请求携带自定义 token
  if (savedToken) {
    config.headers[REQUEST_TOKEN_KEY] = savedToken
  }

  config.params = {
    ...config.params,
    _t: Math.floor(new Date().getTime() / 1000)
  }

  return config
}

// Add a request interceptor
request.interceptors.request.use(requestHandler, errorHandler)

// 响应拦截器
function responseHandler(response) {
  if (response.data.code === 600) {
    console.log('token过期')
    localStorage.removeItem('token');
    // localStorage.remove('token')
    router.push('/')
  }

  return response.data
}

// Add a response interceptor
request.interceptors.response.use(responseHandler, errorHandler)

export default request;
